<template>
  <div class="page-common-layout">
    <div class="page-common-content">
      <!--&lt;!&ndash;登录日志工具栏&ndash;&gt;-->
      <tool-bar
        v-if="activeKey == '1'"
        @search="$refs.loginLog.$refs.table.refresh(true)"
        @reset="
          () => {
            (this.loginLogQueryParam = {}),
              $refs.loginLog.$refs.table.refresh(true);
            this.startTime = [];
          }
        "
      >
        <template slot="toolForm">
          <a-form-item :label="$ct('loginTime', '登录时间')">
            <a-range-picker
              style="width: 280px"
              :ranges="{
                今天: [moment(), moment()],
                最近一周: [moment().add(-1, 'W'), moment()],
                最近一个月: [moment().add(-1, 'M'), moment()],
                最近三个月: [moment().add(-3, 'M'), moment()],
              }"
              :placeholder="[
                $ct('StartTime', '开始时间'),
                $ct('EndTime', '结束时间'),
              ]"
              :valueFormat="'YYYY-MM-DD'"
              @change="startTimeOnChange1"
              v-model="startTime"
            />
          </a-form-item>
          <a-form-item
            :label="$ct('loginAccount', '登录账号')"
            class="margin-right-sm"
          >
            <a-input
              v-model="loginLogQueryParam.userNameId"
              :placeholder="$ct('loginAccount', '登录账号')"
            />
          </a-form-item>
        </template>
      </tool-bar>
      <tool-bar
        v-else-if="activeKey == '2'"
        @search="$refs.operationLog.$refs.table.refresh(true)"
        @reset="
          () => {
            (this.oLogQueryParam = {}),
              $refs.operationLog.$refs.table.refresh(true);
            this.startTime = [];
            this.oLogQueryParam.operationType = 'requestLog.01';
          }
        "
      >
        <!--search -->
        <template slot="toolForm">
          <a-form-item :label="$ct('requestTime', '请求时间')">
            <a-range-picker
              style="width: 280px"
              :ranges="{
                今天: [moment(), moment()],
                最近一周: [moment().add(-1, 'W'), moment()],
                最近一个月: [moment().add(-1, 'M'), moment()],
                最近三个月: [moment().add(-3, 'M'), moment()],
              }"
              :placeholder="[
                $ct('StartTime', '开始时间'),
                $ct('EndTime', '结束时间'),
              ]"
              @change="startTimeOnChange2"
              :valueFormat="'YYYY-MM-DD'"
              v-model="startTime"
            />
          </a-form-item>
          <a-form-item
            :label="$ct('requestAccount', '请求账号')"
            class="margin-right-sm"
          >
            <a-input
              v-model="oLogQueryParam.userNameId"
              :placeholder="$ct('requestAccount', '请求账号')"
            />
          </a-form-item>
          <a-form-item label="项目名称">
            <a-select
              showSearch
              allowClear
              placeholder="请选择项目"
              style="width: 180px"
              v-model="oLogQueryParam.tenantCode"
              :loading="proLoading"
              @popupScroll="handlePopupScroll"
              @search="handleSearchStaff"
              :filter-option="filterOption"
            >
              <a-select-option
                :value="item.proCode"
                v-for="item in curPileSource"
                :key="item.proCode"
              >
                {{ item.proName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </template>
      </tool-bar>
      <!--异常日志-->
      <tool-bar
        v-else-if="activeKey == '3'"
        @search="$refs.errorLog.$refs.table.refresh(true)"
        @reset="
          () => {
            (this.eLogQueryParam = {}),
              $refs.errorLog.$refs.table.refresh(true);
            this.startTime = [];
            this.eLogQueryParam.operationType = 'requestLog.02';
          }
        "
      >
        <!--search -->
        <template slot="toolForm">
          <a-form-item :label="$ct('requestTime', '请求时间')">
            <a-range-picker
              style="width: 280px"
              :ranges="{
                今天: [moment(), moment()],
                最近一周: [moment().add(-1, 'W'), moment()],
                最近一个月: [moment().add(-1, 'M'), moment()],
                最近三个月: [moment().add(-3, 'M'), moment()],
              }"
              :placeholder="[
                $ct('StartTime', '开始时间'),
                $ct('EndTime', '结束时间'),
              ]"
              :valueFormat="'YYYY-MM-DD'"
              @change="startTimeOnChange3"
              v-model="startTime"
            />
          </a-form-item>
          <a-form-item :label="$ct('requestAccount', '请求账号')">
            <a-input
              v-model="eLogQueryParam.userNameId"
              :placeholder="$ct('requestAccount', '请求账号')"
            />
          </a-form-item>
        </template>
      </tool-bar>
      <!-- 表单日志 -->
      <tool-bar
        v-else-if="activeKey == '4'"
        @search="$refs.formLog.$refs.table.refresh(true)"
        @reset="
          () => {
            (this.fLogQueryParam = {}), $refs.formLog.$refs.table.refresh(true);
            this.startTime = [];
            this.fLogQueryParam.operationType = 'requestLog.01';
          }
        "
      >
        <!--search -->
        <template slot="toolForm">
          <a-form-item :label="$ct('requestTime', '请求时间')">
            <a-range-picker
              style="width: 280px"
              :ranges="{
                今天: [moment(), moment()],
                最近一周: [moment().add(-1, 'W'), moment()],
                最近一个月: [moment().add(-1, 'M'), moment()],
                最近三个月: [moment().add(-3, 'M'), moment()],
              }"
              :placeholder="[
                $ct('StartTime', '开始时间'),
                $ct('EndTime', '结束时间'),
              ]"
              @change="startTimeOnChange4"
              :valueFormat="'YYYY-MM-DD'"
              v-model="startTime"
            />
          </a-form-item>
          <a-form-item
            :label="$ct('requestAccount', '请求账号')"
            class="margin-right-sm"
          >
            <a-input
              v-model="fLogQueryParam.userNameId"
              :placeholder="$ct('requestAccount', '请求账号')"
            />
          </a-form-item>
        </template>
      </tool-bar>

      <!--运行日志-->
      <tool-bar
        v-else-if="activeKey == '5'"
        @search="$refs.runLog.$refs.table.refresh(true)"
        @reset="
          () => {
            (this.runQueryParam = {}), $refs.runLog.$refs.table.refresh(true);
            this.startTime = [];
            this.runQueryParam.operationType = 'requestLog.04';
          }
        "
      >
        <!--search -->
        <template slot="toolForm">
          <a-form-item label="创建时间">
            <a-range-picker
              style="width: 280px"
              :ranges="{
                今天: [moment(), moment()],
                最近一周: [moment().add(-1, 'W'), moment()],
                最近一个月: [moment().add(-1, 'M'), moment()],
                最近三个月: [moment().add(-3, 'M'), moment()],
              }"
              :placeholder="[
                $ct('StartTime', '开始时间'),
                $ct('EndTime', '结束时间'),
              ]"
              :valueFormat="'YYYY-MM-DD'"
              @change="startTimeOnChange5"
              v-model="startTime"
            />
          </a-form-item>
        </template>
      </tool-bar>
      <!--日志统计-->
      <tool-bar
        v-else-if="activeKey == '6'"
        @search="searchLogStatistics()"
        @reset="resetLogStatistics()"
      >
        <!--search -->
        <template slot="toolForm">
          <a-form-item label="操作时间">
            <a-range-picker
              style="width: 280px"
              :ranges="{
                今天: [moment(), moment()],
                最近一周: [moment().add(-1, 'W'), moment()],
                最近一个月: [moment().add(-1, 'M'), moment()],
                最近三个月: [moment().add(-3, 'M'), moment()],
              }"
              :placeholder="[
                $ct('StartTime', '开始时间'),
                $ct('EndTime', '结束时间'),
              ]"
              :valueFormat="'YYYY-MM-DD'"
              @change="startTimeOnChange6"
              v-model="logStatisticsTime"
            />
          </a-form-item>
          <a-form-item label="部门">
            <a-tree-select
              style="width:250px"
              v-model="deptCode"
              show-search
              placeholder="请选择部门"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              allow-clear
              tree-default-expand-all
              :loading="deptLoading"
              treeNodeFilterProp="title"
              :replaceFields="{
                children: 'children',
                title: 'orgName',
                key: 'id',
                value: 'id',
              }"
              :tree-data="deptTreeData"
              @change="depeChange($event)"
            >
            </a-tree-select>
          </a-form-item>
        </template>
      </tool-bar>
      <a-tabs
        default-active-key="1"
        :activeKey="activeKey"
        @change="tabsChange"
      >
        <a-tab-pane key="1" tab="登录日志">
          <LoginLog
            ref="loginLog"
            :queryParam="loginLogQueryParam"
            :tableY="tableY"
            @clearAll="clearAll"
          ></LoginLog>
        </a-tab-pane>
        <a-tab-pane key="2" tab="操作日志">
          <OperationLog
            ref="operationLog"
            :queryParam="oLogQueryParam"
            :tableY="tableY"
            @handleEdit="handleEdit"
            @clearAll="clearAll"
          ></OperationLog>
        </a-tab-pane>
        <a-tab-pane key="6" tab="日志统计">
          <logStatistics
            ref="logStatistics"
            :tableY="tableY"
            :startTime="logStatisticsTime"
            :deptCode="deptCode"
          ></logStatistics>
        </a-tab-pane>
        <a-tab-pane key="3" tab="异常日志">
          <ErrorLog
            ref="errorLog"
            :queryParam="eLogQueryParam"
            :tableY="tableY"
            @handleEdit="handleEdit"
            @clearAll="clearAll"
          ></ErrorLog>
        </a-tab-pane>
        <a-tab-pane key="4" tab="表单日志">
          <FormLog
            ref="formLog"
            :queryParam="fLogQueryParam"
            :tableY="tableY"
            @handleEdit="handleEdit"
            @clearAll="clearAll"
          ></FormLog>
        </a-tab-pane>
        <a-tab-pane key="5" tab="运行日志">
          <RunLog
            ref="runLog"
            :queryParam="runQueryParam"
            :tableY="tableY"
            @handleEdit="handleEdit"
            @clearAll="clearAll"
          ></RunLog>
        </a-tab-pane>
      </a-tabs>
    </div>
    <!-- dialog	 -->
    <edit-form
      ref="createModal"
      :visible="visible"
      :model="mdl"
      @cancel="handleCancel()"
      :type="detailType"
    />
  </div>
</template>

<script>
import { mapState } from "vuex";
import moment from "moment";
import { axios } from "@/utils/request";
import LoginLog from "./loginLog.vue";
import OperationLog from "./operationLog.vue";
import logStatistics from "./logStatistics.vue";
import ErrorLog from "./errorLog.vue";
import editForm from "./edit.vue";
import FormLog from "./formlog.vue";
import RunLog from "./runLog.vue";
import { debounce } from "@/utils/util";
import _ from "lodash";
export default {
  name: "index",
  components: {
    LoginLog,
    OperationLog,
    ErrorLog,
    editForm,
    FormLog,
    RunLog,
    logStatistics,
  },
  mounted() {
    this.resizeHandler();
    this.initResizeEvent();
  },
  data() {
    return {
      proLoading: false,
      proSourceData: [],
      curPileSource: [],
      logStatisticsTime: undefined,
      deptLoading: false,
      deptCode: undefined,
      deptTreeData: [],
      visible: false,
      activeKey: "1",
      loginLogQueryParam: {
        startTime: [],
        userNameId: "",
      },
      oLogQueryParam: {
        startTime: [],
        userNameId: "",
        operationType: "requestLog.01",
        tenantCode: undefined,
      },
      eLogQueryParam: {
        startTime: [],
        userNameId: "",
        operationType: "requestLog.02",
      },
      fLogQueryParam: {
        startTime: [],
        userNameId: "",
        operationType: "requestLog.03",
      },
      runQueryParam: {
        startTime: [],
        operationType: "requestLog.04",
      },
      pageClientHeight: "",
      toolbarHeight: "",
      mdl: null,
      detailType: "",
      startTime: [],
    };
  },
  computed: {
    tableY() {
      return this.pageClientHeight - this.toolbarHeight - 195;
    },
    ...mapState("setting", ["divisionBar"]),
  },
  watch: {
    //tabBar样式变化 重新计算
    divisionBar() {
      this.$nextTick(() => {
        this.resizeHandler();
      });
    },
  },
  methods: {
    handleCancel() {
      this.visible = false;
      this.mdl = null;
    },
    handleEdit(record, type) {
      this.visible = true;
      this.mdl = record;
      this.detailType = type;
    },
    //监听resize
    initResizeEvent() {
      window.addEventListener("resize", this.resizeHandler, false);
    },
    resizeHandler() {
      // 获取页面内容的高度
      this.pageClientHeight = document.getElementsByClassName(
        "page-common-layout"
      )[0]?.clientHeight;
      this.toolbarHeight = document.getElementsByClassName(
        "toolbar"
      )[0]?.clientHeight;
    },
    moment,
    //登录日志
    startTimeOnChange1(val) {
      this.loginLogQueryParam.startTime = val.join(",");
    },
    // 操作日志
    startTimeOnChange2(val) {
      this.oLogQueryParam.startTime = val.join(",");
    },
    //异常日志
    startTimeOnChange3(val) {
      this.eLogQueryParam.startTime = val.join(",");
    },
    //表单日志
    startTimeOnChange4(val) {
      this.fLogQueryParam.startTime = val.join(",");
    },
    //运行日志
    startTimeOnChange5(val) {
      this.runQueryParam.startTime = val.join(",");
    },

    //日志统计
    startTimeOnChange6(val) {
      this.logStatisticsTime = val;
      this.$refs.logStatistics.getTableData({
        time: val,
        deptCode: this.deptCode,
      });
    },
    depeChange(val) {
      this.deptCode = val;
      this.$refs.logStatistics.getTableData({
        time: this.logStatisticsTime,
        deptCode: val,
      });
    },

    tabsChange(key) {
      this.activeKey = key;
      this.startTime = [];
      this.loginLogQueryParam = {
        startTime: [],
        userNameId: "",
      };
      this.oLogQueryParam = {
        startTime: [],
        userNameId: "",
        operationType: "requestLog.01",
      };
      this.eLogQueryParam = {
        startTime: [],
        userNameId: "",
        operationType: "requestLog.02",
      };
      this.fLogQueryParam = {
        startTime: [],
        userNameId: "",
        operationType: "requestLog.03",
      };
      if (key == "6") {
        //查询部门树
        this.getdeptData();
        this.$nextTick((_) => {
          this.$refs.logStatistics.getTableData();
        });
      } else if (key == "2") {
        //【操作日志】查询项目名称列表
        this.getProListData();
      }
    },

    //
    //查询项目名称列表
    getProListData() {
      this.proLoading = true;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/mdata/sysProject/queryAllProject`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let data = res || [];
            this.proSourceData = data;
            if (data.length < 20) {
              this.curPileSource = data;
            } else {
              this.curPileSource = data.slice(0, 20);
            }
            resolve();
          })
          .catch((_) => {
            this.proSourceData = res || [];
            resolve();
          })
          .finally((_) => {
            this.proLoading = false;
          });
      });
    },

    // 下拉列表滚动时回调 -- 滚动下拉框，加载更多也就展示更多
    // 实现思路：当前下拉的展示列表+10小于全部数据的长度，newArr为新加载的10条数据，当前展示列表拼上新加载的10条；否则， newArr为全部列表中剩余的数据，当前展示列表拼上剩余的数据。
    handlePopupScroll: _.debounce(function() {
      if (this.proLoading === false) {
        const curLen = this.curPileSource.length;
        const allLen = this.proSourceData.length;
        if (curLen + 10 < allLen) {
          const newArr = this.proSourceData.slice(curLen, curLen + 10);
          this.curPileSource = this.curPileSource.concat(newArr);
        } else {
          const newArr = this.proSourceData.slice(curLen, allLen);
          this.curPileSource = this.curPileSource.concat(newArr);
        }
      }
    }, 200),

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },

    //下拉文本框搜索值变化时回调 -- this.searchName为用户输入的内容，并据此重新发送请求获取过滤后的数据。
    handleSearchStaff: _.debounce(function(val) {
      this.getSelectOptions(val);
      this.searchName = val;
    }, 200),

    getSelectOptions(value = "") {
      if (value == "") {
        this.curPileSource = this.proSourceData.slice(0, 20);
      } else {
        this.curPileSource = this.proSourceData.filter((v) =>
          v.proName.toLowerCase().includes(value.toLowerCase())
        );
      }
      if (this.proSourceData.length < 20) {
        this.curPileSource = this.proSourceData;
      } else {
        this.curPileSource = this.proSourceData.slice(0, 20);
      }
    },

    searchLogStatistics() {
      this.$refs.logStatistics.getTableData({
        time: this.logStatisticsTime,
        deptCode: this.deptCode,
      });
    },
    resetLogStatistics() {
      this.logStatisticsTime = undefined;
      this.deptCode = undefined;
      this.$refs.logStatistics.getTableData();
    },

    //查询部门列表数据
    getdeptData() {
      this.deptLoading = true;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/mdata/transformMdata/getTreeSysOrganizationByUserIdNotPro`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            this.deptTreeData = data || [];
            resolve();
          })
          .catch((_) => {
            this.deptTreeData = [];
            resolve();
          })
          .finally((_) => {
            this.deptLoading = false;
          });
      });
    },

    clearAll() {
      const that = this;
      let url = "/system/sysOperationLog/deleteAllSysOperationLogData";
      let operationType = undefined;
      let containKey = undefined;
      if (that.activeKey == 1) {
        url = "/system/sysLoginLog/deleteAllSysLogLogin";
      } else if (that.activeKey == 2) {
        operationType = "requestLog.01";
      } else if (that.activeKey == 3) {
        operationType = "requestLog.02";
      } else if (that.activeKey == 4) {
        operationType = "requestLog.03";
      } else if (that.activeKey == 5) {
        operationType = "requestLog.04";
      }
      that.$confirm({
        title: that.$ct("tips", "提示"),
        content: "确定要删除所有数据吗？",
        okText: that.$ct("confirm", "确定"),
        cancelText: that.$ct("cancel", "取消"),
        closable: true,
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          return new Promise((resolve, reject) => {
            // 在这里调用删除接口
            that.$post(url, { operationType, containKey }).then((res) => {
              if (res.statusCode === 200) {
                that.$message.success(res.message, 1.5);
                if (that.activeKey == 1) {
                  that.$refs.loginLog.$refs.table.refresh();
                } else if (that.activeKey == 2) {
                  that.$refs.operationLog.$refs.table.refresh();
                } else if (that.activeKey == 3) {
                  that.$refs.errorLog.$refs.table.refresh();
                } else if (that.activeKey == 4) {
                  that.$refs.formLog.$refs.table.refresh();
                } else if (that.activeKey == 5) {
                  that.$refs.runLog.$refs.table.refresh();
                }
                resolve();
              } else {
                that.$message.error(res.message, 1.5);
                reject();
              }
            });
          });
        },
      });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .division-bar {
  margin: 5px -10px 0px -10px !important;
}

/deep/ .ant-table {
  /*margin-bottom: 45px;*/
}
</style>
